package org.hepeng.workx.util.timer;

import io.reactivex.Flowable;
import io.reactivex.Scheduler;
import io.reactivex.functions.Consumer;
import io.reactivex.internal.schedulers.ExecutorScheduler;
import org.hepeng.workx.util.concurrent.NamedThreadFactory;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author he peng
 */
public class Timer {

    private static final ExecutorService EXECUTOR_SERVICE;
    private static final ExecutorScheduler EXECUTOR_SCHEDULER;
    static {
        ThreadFactory threadFactory = new NamedThreadFactory("WorkX-Timer" , true);
        EXECUTOR_SERVICE = new ThreadPoolExecutor(5 , 5 , 0L , TimeUnit.MILLISECONDS , new LinkedBlockingQueue<>() , threadFactory);
        EXECUTOR_SCHEDULER = new ExecutorScheduler(EXECUTOR_SERVICE);
    }

    public static <R> R call(long time , TimeUnit unit , Function<R> func) {

//        Thread thread = Thread.currentThread();
//        long endTime = System.nanoTime() + unit.toNanos(time);
//        Flowable.interval(1 , TimeUnit.NANOSECONDS)
//                .observeOn(EXECUTOR_SCHEDULER)
//                .subscribe(new Consumer<Long>() {
//            @Override
//            public void accept(Long aLong) throws Exception {
//                if (System.nanoTime() >= endTime) {
//                    // 调用超时
//                    thread.interrupt();
//                    Thread.currentThread().interrupt();
//                }
//            }
//        });
        return null;
    }

}
